﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using DotNet.Utilities;
using Entity;
using Utility;

namespace StudentAppointmentPlatform
{
    public partial class ServiceDetail : System.Web.UI.Page, IPostBackEventHandler
    {        
        private AppointmentService service;
        private string didNotChooseDate = "（未选择日期）";

        protected void Page_Load(object sender, EventArgs e)
        {
            string id = Request.QueryString["id"];
            service = ServiceBO.GetServiceByServiceId(id);

            if (service == null || string.IsNullOrWhiteSpace(service.ServiceName))
            {
                Alert.AlertOnPage(Page, "未找到此服务！");
                Redirect.Js_Redirect(Page, "/ShowServices.aspx");
            }
            else
            {
                lbDirectorName.Text = UserBO.GetUserNameById(service.DirectorId);
                lbServiceName.Text = service.ServiceName;
                lbIntroduction.Text = service.Introduction;
                lbTimeBuckets.Text = service.TimeBuckets;
                lbMultiNum.Text = service.MultiNum.ToString();
                lbPerMultiTime.Text = service.PerMultiTime.ToString();
            }

            if (Session["LoginType"].ToString() == "Director")
            {
                btnOrder.Text = "查看";
                MakeOrder.Visible = false;
                CancelOrder.Text = "收起";
            }
        }

        protected void btnBack_OnClick(object sender, EventArgs e)
        {
            Redirect.Js_Redirect2(Page, "/ShowServices.aspx");
        }

        /// <summary>
        /// 弹出预约区的按钮事件;
        /// </summary>
        protected void btnOrder_OnClick(object sender, EventArgs e)
        {           
            OrderArea.Visible = true;
            ChoosedDate.Text = didNotChooseDate;

            Dictionary<string, string> timeBucketsDic = TimeBucket.GetAllTimeBucketsDictionary(service.TimeBuckets, (float)service.PerMultiTime);
            ChooseTime.DataSource = timeBucketsDic;
            ChooseTime.DataTextField = "key";
            ChooseTime.DataValueField = "Value";
            ChooseTime.DataBind();
            ChooseTime.Items.Insert(0, new ListItem("（下拉选择时间段）"));

            RemainNum.Text = string.Empty;
        }       

        protected void Date_OnSelectionChanged(object sender, EventArgs e)
        {
            ChoosedDate.Text = Date.SelectedDate.ToString("yyyy-MM-dd");
            ChooseTime.SelectedIndex = 0; //第0号时间段选项为无效项;
            RemainNum.Text = string.Empty;
        }       

        protected void ChooseTime_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedTime = ChooseTime.SelectedValue;
            if (ChoosedDate.Text == didNotChooseDate)
            {
                Alert.AlertOnPage2(Page, "请先选择日期!");
                ChooseTime.SelectedIndex = 0;
                return;
            }
            if (0 == ChooseTime.SelectedIndex)
            {
                Alert.AlertOnPage2(Page, "请选择有效的时间段!");
                return;
            }

            int reservedNum = RecordBO.GetReservedNum(service.ServiceId, ChoosedDate.Text, selectedTime);
            int remainNum = (int)service.MultiNum - reservedNum;

            if (remainNum > 0)
            {
                RemainNum.Text = remainNum + "(可预约)";
                RemainNum.Style.Add("color", "Green");
            }
            else
            {
                RemainNum.Text = remainNum + "(不可预约,请选择其它时段)";
                RemainNum.Style.Add("color", "Red");
            }
        }

        protected void MakeOrder_OnClick(object sender, EventArgs e)
        {
            bool canBook = false;

            if (ChoosedDate.Text != didNotChooseDate && ChooseTime.SelectedIndex > 0)
            {
                canBook = true;
            }            

            if (canBook)
            {
                string info = "您将预约服务 " + lbServiceName.Text + " ,时间为 " + ChoosedDate.Text + " 的 " +
                              ChooseTime.SelectedItem.Text + " ,您确定要预约吗？";

                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "confirm",
                "if(confirm('" + info + "'))" + ClientScript.GetPostBackEventReference(this, "确定") + "; else " +
                ClientScript.GetPostBackEventReference(this, "取消"), true);
            }
            else
            {
                Alert.AlertOnPage2(Page, "您现在不能预约，可尝试其它时间段。");
            }
        }

        /// <summary>
        /// 提交预约时确认对话框的处理函数;
        /// </summary>       
        public void RaisePostBackEvent(string eventArgument)
        { // 实现IPostBackEventHandler接口的方法;
            switch (eventArgument)
            {
                case "确定":
                    AppointmentRecord record = new AppointmentRecord();
                    record.ServiceId = service.ServiceId;
                    record.ApplicantId = UserBO.GetIdByUserId(Session["UserId"].ToString());
                    record.Day = ChoosedDate.Text;
                    record.TimeBucket = ChooseTime.SelectedValue;
                    record.Status = AppointmentRecord.RecordStatus.Apply.ToString();                   
                    int identity = RecordBO.InsertRecord(record); // 插入预约记录并获取自增长值;

                    Message msg = new Message();
                    msg.UserId = service.DirectorId;
                    msg.MessageContent = @"您管理的服务 " + service.ServiceName + " 已有新的预约，请查看：<a href='/RecordDetail.aspx?AppointmentId=" + identity + "'>预约记录</a>";
                    MessageBO.InsertMessage(msg);

                    Alert.AlertOnPage2(Page, "预约成功！将跳转到预约历史记录页面。");                    
                    OrderArea.Visible = false;
                    Redirect.Js_Redirect2(Page, "/ShowHistory.aspx");

                    break;

                case "取消":
                    OrderArea.Visible = false;
                    break;

                default:
                    throw new NotSupportedException();
            }
        }

        protected void CancelOrder_OnClick(object sender, EventArgs e)
        {
            OrderArea.Visible = false;
        }

        protected void Date_OnDayRender(object sender, DayRenderEventArgs e)
        {
            if (e.Day.Date < DateTime.Now.Date)
            {
                e.Day.IsSelectable = false; // 设置不可选择当天之前的日期;
            }
        }
    }
}